package cn.edu.gzgs.service;

import cn.edu.gzgs.entity.EmailMsg;
import cn.edu.gzgs.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * WebSocket消息发送服务
 */
@Slf4j
@Service
public class WebSocketMessageService {

    @Autowired
    private EmailMsgService emailMsgService;

    /**
     * 发送项目申请被拒绝通知
     */
    public void sendProjectRepulseNotification(String userId, String projectName, String reason) {
        sendProjectRepulseNotification(userId, projectName, reason, "system", "系统通知");
    }
    
    /**
     * 发送项目申请被拒绝通知（指定发送者）
     */
    public void sendProjectRepulseNotification(String userId, String projectName, String reason, String senderId, String senderName) {
        try {
            // 保存到数据库
            EmailMsg emailMsg = new EmailMsg();
            emailMsg.setSenderId(senderId);
            emailMsg.setSenderName(senderName);
            emailMsg.setAcceptId(userId);
            emailMsg.setTitle("申请不通过");
            emailMsg.setContent(reason != null && !reason.trim().isEmpty() ? reason : "");
            emailMsg.setType("routerTo_Project_Repulse");
            emailMsg.setTime(LocalDateTime.now());
            emailMsg.setIsRead(false);

            boolean saved = emailMsgService.sendEmail(emailMsg);
            
            if (saved) {
                // WebSocket实时推送在EmailMsgService.sendEmail中已处理
                log.info("项目拒绝通知发送成功: 发送者={}, 用户={}, 项目={}", senderName, userId, projectName);
            } else {
                log.error("项目拒绝通知保存失败: 发送者={}, 用户={}, 项目={}", senderName, userId, projectName);
            }
        } catch (Exception e) {
            log.error("发送项目拒绝通知失败", e);
        }
    }

    /**
     * 发送项目申请通过通知
     */
    public void sendProjectPassNotification(String userId, String projectName) {
        sendProjectPassNotification(userId, projectName, "system", "系统通知");
    }
    
    /**
     * 发送项目申请通过通知（指定发送者）
     */
    public void sendProjectPassNotification(String userId, String projectName, String senderId, String senderName) {
        try {
            EmailMsg emailMsg = new EmailMsg();
            emailMsg.setSenderId(senderId);
            emailMsg.setSenderName(senderName);
            emailMsg.setAcceptId(userId);
            emailMsg.setTitle("申请通过");
            emailMsg.setContent("恭喜！您的工作量申报已通过审核");
            emailMsg.setType("routerTo_Project_Pass");
            emailMsg.setTime(LocalDateTime.now());
            emailMsg.setIsRead(false);

            boolean saved = emailMsgService.sendEmail(emailMsg);
            
            if (saved) {
                log.info("项目通过通知发送成功: 发送者={}, 用户={}, 项目={}", senderName, userId, projectName);
            } else {
                log.error("项目通过通知保存失败: 发送者={}, 用户={}, 项目={}", senderName, userId, projectName);
            }
        } catch (Exception e) {
            log.error("发送项目通过通知失败", e);
        }
    }

    /**
     * 发送通知消息
     */
    public void sendInformMessage(String userId, String title, String content) {
        try {
            EmailMsg emailMsg = new EmailMsg();
            emailMsg.setSenderId("system");
            emailMsg.setSenderName("系统通知");
            emailMsg.setAcceptId(userId);
            emailMsg.setTitle(title);
            emailMsg.setContent(content);
            emailMsg.setType("general_Msg_Inform");
            emailMsg.setTime(LocalDateTime.now());
            emailMsg.setIsRead(false);

            boolean saved = emailMsgService.sendEmail(emailMsg);
            
            if (saved) {
                log.info("通知消息发送成功: 用户={}, 标题={}", userId, title);
            } else {
                log.error("通知消息保存失败: 用户={}, 标题={}", userId, title);
            }
        } catch (Exception e) {
            log.error("发送通知消息失败", e);
        }
    }

    /**
     * 发送系统消息
     */
    public void sendSystemMessage(String userId, String title, String content) {
        try {
            EmailMsg emailMsg = new EmailMsg();
            emailMsg.setSenderId("system");
            emailMsg.setSenderName("系统管理员");
            emailMsg.setAcceptId(userId);
            emailMsg.setTitle(title);
            emailMsg.setContent(content);
            emailMsg.setType("general_Msg_System");
            emailMsg.setTime(LocalDateTime.now());
            emailMsg.setIsRead(false);

            boolean saved = emailMsgService.sendEmail(emailMsg);
            
            if (saved) {
                log.info("系统消息发送成功: 用户={}, 标题={}", userId, title);
            } else {
                log.error("系统消息保存失败: 用户={}, 标题={}", userId, title);
            }
        } catch (Exception e) {
            log.error("发送系统消息失败", e);
        }
    }

    /**
     * 发送私信
     */
    public void sendPrivateMessage(String senderId, String senderName, String acceptId, String title, String content) {
        try {
            EmailMsg emailMsg = new EmailMsg();
            emailMsg.setSenderId(senderId);
            emailMsg.setSenderName(senderName);
            emailMsg.setAcceptId(acceptId);
            emailMsg.setTitle(title);
            emailMsg.setContent(content);
            emailMsg.setType("general_Msg_Private");
            emailMsg.setTime(LocalDateTime.now());
            emailMsg.setIsRead(false);

            boolean saved = emailMsgService.sendEmail(emailMsg);
            
            if (saved) {
                log.info("私信发送成功: {} -> {}, 标题={}", senderId, acceptId, title);
            } else {
                log.error("私信保存失败: {} -> {}, 标题={}", senderId, acceptId, title);
            }
        } catch (Exception e) {
            log.error("发送私信失败", e);
        }
    }

    /**
     * 强制用户下线
     */
    public void forceUserOffline(String userId, String reason) {
        WebSocketServer.forceUserOffline(userId, reason);
        log.info("用户 {} 被强制下线，原因：{}", userId, reason);
    }
}